<template>
  <view class="address-page">
    <!-- 地址列表 -->
    <view class="address-list" v-if="addressList.length > 0">
      <view 
        class="address-item" 
        v-for="(item, index) in addressList" 
        :key="item.id"
      >
        <view class="address-info" @click="selectAddress(item)">
          <view class="address-top">
            <text class="name">{{ item.name }}</text>
            <text class="phone">{{ formatPhone(item.phone) }}</text>
          </view>
          <view class="address-tags">
            <text 
              class="tag default-tag" 
              v-if="item.isDefault"
            >默认</text>
          </view>
          <view class="address-detail">
            <text class="detail-text">{{ item.province }}{{ item.city }}{{ item.area }}{{ item.address }}</text>
          </view>
        </view>
        <view class="address-actions">
          <view class="action-btn edit-btn" @click="editAddress(item)">
            <up-icon name="edit-pen" size="20" color="#666"></up-icon>
            <text>编辑</text>
          </view>
          <view class="action-btn delete-btn" @click="deleteAddress(item, index)">
            <up-icon name="trash" size="20" color="#666"></up-icon>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空地址提示 -->
    <view class="empty-address" v-else>
      <up-icon name="order" size="60" color="#ccc"></up-icon>
      <text class="empty-text">暂无收货地址</text>
    </view>

    <!-- 添加地址按钮 -->
    <view class="add-address-btn">
      <up-button 
        type="primary" 
        shape="circle" 
        icon="plus"
        text="新增地址"
        @click="addAddress"
      ></up-button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

const addressList = ref([])

// 获取地址列表
const getAddressList = () => {
  // 模拟从本地存储获取地址数据
  try {
    const storedAddresses = uni.getStorageSync('userAddresses') || []
    addressList.value = storedAddresses
  } catch (error) {
    console.error('获取地址列表失败:', error)
    addressList.value = []
  }
}

// 新增地址
const addAddress = () => {
  uni.navigateTo({
    url: '/pages/user/address/edit'
  })
}

// 编辑地址
const editAddress = (address) => {
  uni.navigateTo({
    url: `/pages/user/address/edit?id=${address.id}`
  })
}

// 删除地址
const deleteAddress = (address, index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个收货地址吗？',
    success: (res) => {
      if (res.confirm) {
        addressList.value.splice(index, 1)
        // 更新本地存储
        saveAddresses()
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 选择地址（用于下单时选择）
const selectAddress = (address) => {
  // 如果是从下单页面跳转过来的，需要返回选中的地址
  const pages = getCurrentPages()
  const prevPage = pages[pages.length - 2] // 上一个页面
  
  if (prevPage && prevPage.route.includes('order')) {
    // 将选中的地址传递回上一个页面
    uni.$emit('selectAddress', address)
    uni.navigateBack()
  }
}

// 保存地址到本地存储
const saveAddresses = () => {
  try {
    uni.setStorageSync('userAddresses', addressList.value)
  } catch (error) {
    console.error('保存地址失败:', error)
  }
}

// 页面加载时获取地址列表
onMounted(() => {
  getAddressList()
})

onLoad(() => {
  getAddressList()
})

// 添加 onShow 钩子，确保每次页面显示时都刷新地址列表
onShow(() => {
  getAddressList()
})

// 监听地址更新事件
uni.$on('addressUpdated', () => {
  getAddressList()
})

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('addressUpdated')
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 格式化手机号
const formatPhone = (phone) => {
  return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}

</script>

<style lang="scss" scoped>
.address-page {
  min-height: 95vh;
  background-color: #f5f5f5;
  padding: 20rpx;
  
  .address-list {
    // margin-top: 10rpx;
    .address-item {
      background-color: #fff;
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      display: flex;
      align-items: center;
      
      .address-info {
        flex: 1;
        
        .address-top {
          display: flex;
          align-items: center;
          margin-bottom: 16rpx;
          
          .name {
            font-size: 32rpx;
            font-weight: 600;
            color: #333;
            margin-right: 20rpx;
          }
          
          .phone {
            font-size: 28rpx;
            color: #666;
            flex: 1;
          }
        }
        
        .address-tags {
          display: flex;
          margin-bottom: 16rpx;
          
          .tag {
            background-color: #ff6b35;
            color: #fff;
            font-size: 20rpx;
            padding: 4rpx 12rpx;
            border-radius: 8rpx;
            margin-left: 16rpx;
          }
          
          .default-tag {
            background-color: #ff6b35;
          }
        }
        
        .address-detail {
          .detail-text {
            font-size: 26rpx;
            color: #666;
            line-height: 1.5;
          }
        }
      }
      
      .address-actions {
        display: flex;
        gap: 30rpx;
        
        .action-btn {
          display: flex;
          align-items: center;
          gap: 10rpx;
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
  
  .empty-address {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 100rpx 40rpx;
    text-align: center;
    
    .empty-text {
      display: block;
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .add-address-btn {
    position: fixed;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
  }
}
</style>